#include "parsing.h"

int split_line(char* line,char* fields[MAXFIELDS]){
    int ll=strlen(line);
    int i;
    int ncols=0,rl=0,rs=0; //running length running spaces
    char c;
    for(i=0;i<ll;i++){
        c = line[i];
        if (isspace(c)){
            if (rs++==0) {fields[ncols++][rl]='\0';rl=0; continue;}
            continue;
        } else {
            fields[ncols][rl++]=c;
            rs=0;
        }
    }
    return ncols;
}

void parse_pileup(char ref, char* pileup, char* qualities, int* parsed){
	/* parsed contains the following fields:
	 0 number (#) of '.' or ',' characters (reference)
	 1 #A
	 2 #C
	 3 #G
	 4 #T	
	 5 #N
	 6 qA
	 7 qC
	 8 qG
	 9 qT			
	 10 sum of the quality codes for reference symbols
	 11 sum of quality codes for non reference symbols
	 12 the first 8 LSB bits indicate in which strand each character has been observed 
	 MSB TGCA(R)TGCA(F) LSB
	     0000   0000
	 */ 
	int le = strlen(pileup);
	if (0==le) {fprintf(stderr,"libparsepileup:empty pileup\n"); exit(1);}
	int i=0,pos=0; /* i is the index along the pileup, pos is the index along the qualities*/			
	while (i<le){
		char c=pileup[i];
		switch(c){
			case 'A':
				parsed[1]++;parsed[6]+=qualities[pos++];parsed[12]|=1;break;
			case 'a':
				parsed[1]++;parsed[6]+=qualities[pos++];parsed[12]|=16;break;
			case 'C':
				parsed[2]++;parsed[7]+=qualities[pos++];parsed[12]|=2;break;
			case 'c':
				parsed[2]++;parsed[7]+=qualities[pos++];parsed[12]|=32;break;
			case 'G':
				parsed[3]++;parsed[8]+=qualities[pos++];parsed[12]|=4;break;
			case 'g':
				parsed[3]++;parsed[8]+=qualities[pos++];parsed[12]|=64;break; 
			case 'T':
				parsed[4]++;parsed[9]+=qualities[pos++];parsed[12]|=8;break;
			case 't':
				parsed[4]++;parsed[9]+=qualities[pos++];parsed[12]|=128;break; 
			case 'N':
				parsed[5]++;parsed[11]+=qualities[pos++];break;
			case '.':
				switch(ref){
					case 'A':parsed[1]++;parsed[6]+=qualities[pos];parsed[12]|=1; break;
					case 'C':parsed[2]++;parsed[7]+=qualities[pos];parsed[12]|=2; break;
					case 'G':parsed[3]++;parsed[8]+=qualities[pos];parsed[12]|=4; break;
					case 'T':parsed[4]++;parsed[9]+=qualities[pos];parsed[12]|=8; break;
					case 'N':parsed[5]++;parsed[11]+=qualities[pos]; break;
					default: exit(1);
				}
				parsed[0]++;parsed[10]+=qualities[pos++];break;
			case ',':
				switch(ref){
					case 'A':parsed[1]++;parsed[6]+=qualities[pos];parsed[12]|=16; break;
					case 'C':parsed[2]++;parsed[7]+=qualities[pos];parsed[12]|=32; break;
					case 'G':parsed[3]++;parsed[8]+=qualities[pos];parsed[12]|=64; break;
					case 'T':parsed[4]++;parsed[9]+=qualities[pos];parsed[12]|=128; break;
					case 'N':parsed[5]++;parsed[11]+=qualities[pos]; break;
					default: exit(1);
				}
				parsed[0]++; parsed[10]+=qualities[pos++];break;
			case '$':
				i++; continue;
			case '^':
				i+=2; continue;
			case '<':
			case '>': i++; pos++; continue;	
		}
		i++; /* position along the pileup advances anyway */		
	}
}

